﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace MO.ModelingClient
{
    public partial class ItemChildTableControl : ItemBaseControl
    {
        DataConfig config;
        string title;
        public ItemChildTableControl(string title, DataConfig config, string parentField, string parentValue)
        {
            InitializeComponent();
            base.Init(title);
            if (string.IsNullOrEmpty(parentValue))
            {
                this.buttonOk.Enabled = false;
                return;
            }
            foreach (ItemData item in config.FieldList)
            {
                if (item.Code == config.KeyField)
                {
                    item.Default = parentValue + "_";
                    break;
                }
            }
            config.KeyDict[parentField] = parentValue;
            this.config = config;
            this.title = title;
            SetText();
            
        }
        void SetText()
        {
            List<string> whereList = new List<string>();
            foreach (var item in config.KeyDict)
            {
                if (item.Value is string)
                    whereList.Add(item.Key + " = '" + item.Value + "'");
                else
                    whereList.Add(item.Key + " = " + item.Value);
            }
            string sqlStr = "select " + config.TitleField + " from " + config.TableName;
            if (config.KeyDict.Count > 0)
                sqlStr += " where " + string.Join(" and ", whereList.ToArray());
            if (!string.IsNullOrEmpty(config.OrderField))
            {
                sqlStr += " order by " + config.OrderField;
            }
            DataTable table = DbOperation.DB.ExecuteDataTable(sqlStr);
            List<string> list = new List<string>();
            foreach (DataRow row in table.Rows)
            {
                list.Add(row[0].ToString());
            }
            this.textBox.Text = string.Join(",", list.ToArray());
        }
        public override void SetEnabled(bool enabled)
        {
            this.buttonOk.Enabled = enabled;
        }
        private void buttonOk_Click(object sender, EventArgs e)
        {
            TableForm form = new TableForm(title, config);
            form.ShowDialog(this.FindForm());
            SetText();
        }
    }
}
